package com.example.common.tools

import android.os.Environment
import android.util.Log
import java.io.*
import java.text.SimpleDateFormat
import java.util.*


object LogUtils {

    private var IS_DEBUG = false

    private val MYLOG_PATH_SDCARD_DIR = "/sdcard/sound/log"// 日志文件在sdcard中的路径
    private val MYLOG_PATH_SDCARD_TEXT = "/sdcard/sound"// 日志文件在sdcard中的路径
    private val logfile = SimpleDateFormat("yyyy-MM-dd")// 日志文件格式
    private val writefile = SimpleDateFormat("yyyy-MM-dd-HH:mm:ss")// 日志文件格式
    private val MYLOGFILEName = "Log.txt"// 本类输出的日志文件名称
    private val myLogSdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")// 日志的输出格式
    private var SDCARD_LOG_FILE_SAVE_DAYS = 0// sd卡中日志文件的最多保存天数
    private var isWriteLogto = false
    private val format = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")

    fun setDebug(isDebug: Boolean): LogUtils {
        IS_DEBUG = isDebug
        return this
    }

    //设置日志保存天数
    fun setLogSaveDay(day: Int) {
        SDCARD_LOG_FILE_SAVE_DAYS = day
    }

    fun setWriteLogto(isWriteLogto: Boolean) {
        LogUtils.isWriteLogto = isWriteLogto
    }

    private val TAG = "baseTool"

    fun e(tag: String, msg: String) {
        if (IS_DEBUG) Log.e(tag, msg)
    }

    fun i(tag: String, msg: String) {
        if (IS_DEBUG) Log.i(tag, msg)
        writeLogtoFile(TAG, TAG, msg)
    }

    fun d(tag: String, msg: String) {
        if (IS_DEBUG) Log.d(tag, msg)
        writeLogtoFile(TAG, TAG, msg)
    }

    fun v(tag: String, msg: String) {
        if (IS_DEBUG) Log.v(tag, msg)
        writeLogtoFile(TAG, TAG, msg)
    }

    fun w(tag: String, msg: String) {
        if (IS_DEBUG) Log.w(tag, msg)
        writeLogtoFile(TAG, TAG, msg)
    }

    fun e(msg: String) {
        if (IS_DEBUG) Log.e(TAG, msg)
        writeLogtoFile(TAG, TAG, msg)
    }

    fun i(msg: String) {
        i(TAG, msg)
    }

    fun d(msg: String) {
        d(TAG, msg)
    }

    fun v(msg: String) {
        v(TAG, msg)
    }

    fun w(msg: String) {
        w(TAG, msg)
    }

    fun i(tag: String, e: Throwable) {
        if (IS_DEBUG) {
            val info = StringWriter()
            val printWriter = PrintWriter(info)
            e.printStackTrace(printWriter)

            var cause: Throwable? = e.cause
            while (cause != null) {
                cause.printStackTrace(printWriter)
                cause = cause.cause
            }
            i(tag, info.toString())
        }
    }

    fun i(e: Throwable) {
        if (IS_DEBUG) {
            i(TAG, e)
        }
    }

    //规定每段显示的长度
    private val LOG_MAXLENGTH = 2000

    /**
     * @author wangyajie
     * @Description: 解决json过长系统log无法打印全
     * @buildDate 2018/5/15 14:21
     */
    fun eLog(TAG: String, msg: String) {
        if (IS_DEBUG) {
            val strLength = msg.length
            var start = 0
            var end = LOG_MAXLENGTH
            for (i in 0..99) {
                //剩下的文本还是大于规定长度则继续重复截取并输出
                if (strLength > end) {
                    Log.e(TAG + i, msg.substring(start, end))
                    start = end
                    end = end + LOG_MAXLENGTH
                } else {
                    Log.e(TAG, msg.substring(start, strLength))
                    writeLogtoFile(TAG, TAG, msg)
                    break
                }
            }
        }

    }

    fun dataE(TAG: String, msg: String) {
        var date = Date(System.currentTimeMillis())
        eLog(TAG, "${format.format(date)}------->${msg}")
    }

    /**
     * 打开日志文件并写入日志
     * @param mylogtype
     * @param tag
     * @param text
     */
    private fun writeLogtoFile(mylogtype: String, tag: String, text: String) {// 新建或打开日志文件
        if (isWriteLogto) {
            val nowtime = Date()
            val needWriteFiel = logfile.format(nowtime)
            val needWriteMessage =
                myLogSdf.format(nowtime) + "    " + mylogtype + "    " + tag + "    " + text

            val dirsFile = File(MYLOG_PATH_SDCARD_DIR)
            if (!dirsFile.exists()) {
                dirsFile.mkdirs()
            }
            //Log.i("创建文件","创建文件");
            val file =
                File(dirsFile.toString(), needWriteFiel + MYLOGFILEName)// MYLOG_PATH_SDCARD_DIR
            if (!file.exists()) {
                try {
                    //在指定的文件夹中创建文件
                    file.createNewFile()
                } catch (e: Exception) {
                }
            }

            try {
                val filerWriter = FileWriter(file, true)// 后面这个参数代表是不是要接上文件中原来的数据，不进行覆盖
                val bufWriter = BufferedWriter(filerWriter)
                bufWriter.write(needWriteMessage)
                bufWriter.newLine()
                bufWriter.close()
                filerWriter.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

    /**
     * 删除制定的日志文件
     */
    fun delFile() {// 删除日志文件
        val needDelFiel = logfile.format(getDateBefore())
        val dirPath = Environment.getExternalStorageDirectory()
        val file = File(dirPath, needDelFiel + MYLOGFILEName)// MYLOG_PATH_SDCARD_DIR
        if (file.exists()) {
            file.delete()
        }
    }


    /**
     * 输出日志
     * @param mylogtype
     * @param tag
     * @param text
     */
//    fun writeTextFile(contex: Context, textName: String, tag: String, text: String) {// 新建或打开日志文件
//        val nowtime = Date()
//        val needWriteFiel = writefile.format(nowtime)
//        val needWriteMessage = "时间： ${writefile.format(nowtime)} ---> $tag :   $text"
//
//
//        val dirsFile = File(MYLOG_PATH_SDCARD_TEXT)
//        if (!dirsFile.exists()) {
//            dirsFile.mkdirs()
//        }
//        //Log.i("创建文件","创建文件");
//        val file =
//            File(dirsFile.toString(), "${textName}$needWriteFiel.txt")// MYLOG_PATH_SDCARD_DIR
//        if (!file.exists()) {
//            try {
//                //在指定的文件夹中创建文件
//                file.createNewFile()
//            } catch (e: Exception) {
//                "文件创建失败 ${e.message}".toast(contex)
//            }
//        }
//
//        try {
//            val filerWriter = FileWriter(file, true)// 后面这个参数代表是不是要接上文件中原来的数据，不进行覆盖
//            val bufWriter = BufferedWriter(filerWriter)
//            bufWriter.write(needWriteMessage)
//            bufWriter.newLine()
//            bufWriter.close()
//            filerWriter.close()
//            val list = SPUtils.getList(contex, "TEXT_FILE")
//            list.add(file.absolutePath)
//            SPUtils.putList(contex, "TEXT_FILE", list)
//            "文件保存成功".toast(contex)
//        } catch (e: IOException) {
//            "文件输出失败 ${e.message}".toast(contex)
//        }
//    }

    /**
     * 删除制定的日志文件
     */
    fun delTextFile(time: Long) {// 删除日志文件
        val needDelFiel = logfile.format(getDateBefore())
        val dirPath = Environment.getExternalStorageDirectory()
        val file = File(dirPath, needDelFiel + MYLOGFILEName)// MYLOG_PATH_SDCARD_DIR
        if (file.exists()) {
            file.delete()
        }
    }

    /**
     * 得到现在时间前的几天日期，用来得到需要删除的日志文件名
     */
    private fun getDateBefore(): Date {
        val nowtime = Date()
        val now = Calendar.getInstance()
        now.time = nowtime
        now.set(Calendar.DATE, now.get(Calendar.DATE) - SDCARD_LOG_FILE_SAVE_DAYS)
        return now.time
    }

}

